package com.lab.utils;

import android.view.View;
import android.widget.TextView;

import com.amap.api.maps2d.model.Text;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by sheena on 16/5/14.
 */
public class RxUtils {
    /**
     * @param time     倒计总时长
     * @param textView 按钮（本项目中按钮都用textview)
     * @param text     按钮中的文本文字
     */
    public static void countDownBySeconds(final int time, final TextView textView, final String text) {
        Observable<Void> verifyCodeObservable = RxView.clicks(textView).throttleFirst(time, TimeUnit.SECONDS).subscribeOn(AndroidSchedulers.mainThread());
        verifyCodeObservable.subscribe(
                new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Observable.timer(0, 1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()).take(time).
                                subscribe(new Observer<Long>() {
                                    @Override
                                    public void onCompleted() {
                                        textView.setText(text);
                                        textView.setEnabled(true);
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(Long aLong) {
                                        textView.setEnabled(false);
                                        textView.setText(time - aLong + "");

                                    }
                                });
                    }
                });

    }


}
